﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Pub.Tools;
using System.IO;
using System.Xml;
using System.Threading;
using System.Reflection;

namespace Tools
{
    public partial class FrmTools : Form
    {
        public FrmTools()
        {
            InitializeComponent();
        }

        const string FILENAME = "updateservice.xml";

        private void btnEN_Click(object sender, EventArgs e)
        {
            txt2.Text = DESEncrypt.Encrypt(txt1.Text);
        }

        private void btnDe_Click(object sender, EventArgs e)
        {
            txt2.Text = DESEncrypt.Decrypt(txt1.Text);
        }

        private void btnFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            //    openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            openFileDialog.Filter = "所有文件(*.*)|*.*";
            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                labFile.Text = openFileDialog.FileName;
                string ext = System.IO.Path.GetExtension(labFile.Text).ToLower();
                if (ext == ".zip")
                {
                    txtFile.Text = System.IO.Path.ChangeExtension(openFileDialog.FileName, "zzz");   //返回指定路径字符串的文件名
                }
                else
                {
                    txtFile.Text = openFileDialog.FileName + ".zip";
                }
            }
        }

        private void btnComFile_Click(object sender, EventArgs e)
        {
            if (File.Exists(labFile.Text))
            {
                ZipFile.CompressFile(labFile.Text, txtFile.Text);
                MsgTools.InfoMsg("OK");
            }
        }

        private void btnDecFile_Click(object sender, EventArgs e)
        {
            if (File.Exists(labFile.Text))
            {
                ZipFile.DecompressFile(labFile.Text, txtFile.Text);
                MsgTools.InfoMsg("OK");
            }
        }

        private void CopyStream1(Stream src, string filename)
        {
            //dest.Position = 0;
            StreamReader reader = new StreamReader(src);
            Stream dest = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None);
            StreamWriter writer = new StreamWriter(dest);

            writer.Write(reader.ReadToEnd());
            writer.Flush();

            writer.Close();
            writer.Dispose();
            dest.Close();
            dest.Dispose();
            reader.Close();
            reader.Dispose();
        }

        private void CopyStream(MemoryStream m, string filename)
        {
            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filename);
            FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate);
            BinaryWriter w = new BinaryWriter(fs);
            w.Write(m.ToArray());
            fs.Close();

        }


        private void NodeAttribAdd(XmlDocument doc, XmlNode _node, string nodename)
        {
            if (_node.Attributes[nodename] == null)
            {
                XmlAttribute _nodeatt = doc.CreateAttribute(nodename);
                _node.Attributes.Append(_nodeatt);
            }
        }

        private  Boolean ShowElementCount(Array array)
        {
            Boolean bl = true;
            Dictionary<object, int> dic = new Dictionary<object, int>();
            foreach (object o in array)
            {
                if (!dic.ContainsKey(o))
                    dic.Add(o, 1);
                else
                    dic[o]++;
            }
            foreach (object o in dic.Keys)
            {
                if (dic[o] > 1)
                {
                    bl = false;
                    MsgTools.ErrorMsg(string.Format("配置文件{0}出错,\r\n{1}重复出现了{2}次.",FILENAME, o, dic[o]));
                }
            }
            return bl;
        }

        private void btnAutoUpdate_Click(object sender, EventArgs e)
        {

            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
            richTextBox1.Clear();

            XmlDocument doc = new XmlDocument();
            doc.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, FILENAME));
            XmlNode xnuser = doc.SelectSingleNode("update/updateFiles");
            XmlNodeList xl = xnuser.ChildNodes;//读取所有Student节点
            string[] strArr = new string[xnuser.ChildNodes.Count];
            for (int i = 0; i < xnuser.ChildNodes.Count; i++)
            {
                XmlNode _node = xnuser.ChildNodes[i];
                string urlpath = _node.Attributes["Path"].InnerText;
                strArr[i] = urlpath;
            }
            if (!ShowElementCount(strArr)) 
            {
                System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
                return; 
            }

            panupdate.Visible = true;
            for (int i = 0; i < xnuser.ChildNodes.Count; i++)
            {
                XmlNode _node = xnuser.ChildNodes[i];
                string urlpath = _node.Attributes["Path"].InnerText;


                int ii = urlpath.ToLower().IndexOf("http://", 0);
                if (ii == -1)
                {
                    string path = urlpath.Replace("/", @"\");
                    string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path);

                    labfn.Text = filePath;
                    this.Refresh();


                    NodeAttribAdd(doc, _node, "LastWriteTime");
                    NodeAttribAdd(doc, _node, "Size");
                    NodeAttribAdd(doc, _node, "ZipSize");
                    NodeAttribAdd(doc, _node, "LastVer");
                    NodeAttribAdd(doc, _node, "Url");
                    NodeAttribAdd(doc, _node, "Zip");

                    if (File.Exists(filePath))
                    {


                        //根据扩展名是mdb,先压缩.
                        string ext = System.IO.Path.GetExtension(filePath);
                        if (ext.ToLower() == ".mdb".ToLower())
                        {
                            CompactAccessDB(filePath, string.Empty);
                        }
                        System.Diagnostics.FileVersionInfo myFileVersionInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo(filePath);
                        string FileVersion = string.Empty;
                        if (myFileVersionInfo.FileVersion != null)
                        {
                            FileVersion = myFileVersionInfo.FileVersion;
                        }

                        FileInfo fi = new FileInfo(filePath);
                        string WriteTime = fi.LastWriteTime.ToString();
                        long iSzie = fi.Length;

                        //判断是否是新旧文件
                        if (!((rbNedd.Checked) && (_node.Attributes["LastWriteTime"].InnerText == WriteTime) && (_node.Attributes["LastVer"].InnerText == FileVersion) && (File.Exists(filePath + ".Zip"))))
                        {

                            _node.Attributes["LastWriteTime"].InnerText = WriteTime;
                            _node.Attributes["LastVer"].InnerText = FileVersion;
                            _node.Attributes["Size"].InnerText = iSzie.ToString();
                            _node.Attributes["Url"].InnerText = urlpath + ".Zip";
                            _node.Attributes["Zip"].InnerText = "True";


                            ZipFile.CompressFile(filePath, filePath + ".Zip");

                            fi = new FileInfo(filePath + ".Zip");
                            WriteTime = fi.LastWriteTime.ToString();
                            long iZipSzie = fi.Length;
                            //size = fi.Length.ToString();

                            _node.Attributes["ZipSize"].InnerText = iZipSzie.ToString();

                            //压缩后文件反而大的情况,用源文件
                            if (iZipSzie > iSzie)
                            {
                                try
                                {
                                    File.Copy(filePath, filePath + ".Zip", true);
                                    System.IO.File.SetAttributes(filePath + ".Zip", System.IO.FileAttributes.Normal); //去文件只读属性
                                }
                                catch
                                {
                                }

                                _node.Attributes["ZipSize"].InnerText = iSzie.ToString();
                                _node.Attributes["Zip"].InnerText = "False";
                            }
                            richTextBox1.AppendText(_node.Attributes["Path"].InnerText + "\n");

                        }

                    }

                }
                progressBarEx1.Value = (i + 1) * 100 / xnuser.ChildNodes.Count;
            }

            string savefile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, FILENAME);
            string strdocxml = doc.InnerXml.ToString();
            SysTools.WriteTxt(savefile, strdocxml, FileMode.Create);


          //  doc.Save(savefile);

            string ZipFileName = savefile + ".zip";
            if (File.Exists(ZipFileName))
            {
                File.Delete(ZipFileName);
            }

            strdocxml = ZipString.CompressString(strdocxml);

            SysTools.WriteTxt(ZipFileName, strdocxml,FileMode.Create);


         //   ZipFile.CompressFile(savefile, ZipFileName);
   //         panupdate.Visible = false;
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;

            MsgTools.InfoMsg("自动升级配置完成.");
        }

        private void FrmTools_Load(object sender, EventArgs e)
        {
            this.gridEx1.AutoGenerateColumns = false;
            this.Height = (int)(Screen.PrimaryScreen.Bounds.Height * 0.9);
            this.Width = (int)(Screen.PrimaryScreen.Bounds.Width * 0.9);
            this.Left = (Screen.PrimaryScreen.Bounds.Width - this.Width) / 2;
            this.Top = (Screen.PrimaryScreen.Bounds.Height - this.Height) / 2;

            System.AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "App.config");
            this.dataTableEx1.DataBinds();
        
            this.bindingSource1.DataSource = this.dataTableEx1.DataTable;

         //   this.textBox1.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bindingSource1, "cSQL", true));

            number1.DataBindings.Add("text", this.bindingSource1, "cSQL");

            this.tabPage2.Parent = null; //隐藏
            this.tabPage3.Parent = null; //隐藏
            //   tabControl1.SelectedTab = tabControl1.TabPages[2];
        }

        private string GetTempFile(string fFile)
        {
            string extFn = Path.GetExtension(fFile);
            string fFn = fFile.Substring(0, fFile.Length - extFn.Length);
            string strdate = string.Format("_{0:yyyyMMddHHmmssffff}", System.DateTime.Now);
            string strFile = fFn + strdate + extFn;
            while (File.Exists(strFile))
            {
                fFn = fFile.Substring(0, fFile.Length - extFn.Length);
                strFile = fFn + strdate + extFn;
            }
            return strFile;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show(GetTempFile("a.txt").ToString());
        }

        private void panel4_DoubleClick(object sender, EventArgs e)
        {
            this.tabPage2.Parent = this.tabControl1;//显示
            this.tabPage3.Parent = this.tabControl1;//显示
        }

        public static void CompactAccessDB(string accessDbPath, string pass)
        {
            try
            {
                string tempDbPth = ".bak";

                tempDbPth = accessDbPath.Substring(0, accessDbPath.LastIndexOf("") + 1) + tempDbPth;

                string connectString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Database Password={1}";

                string tempDbConnectiongString = string.Format(connectString, tempDbPth, pass);

                string objectDbConnectiongString = string.Format(connectString, accessDbPath, pass);

                object[] oParams;


                object objJRO = Activator.CreateInstance(Type.GetTypeFromProgID("JRO.JetEngine"));
                oParams = new object[] { objectDbConnectiongString, tempDbConnectiongString };

                objJRO.GetType().InvokeMember("CompactDatabase",
                System.Reflection.BindingFlags.InvokeMethod,
                null,
                objJRO,
                oParams);



                File.Copy(tempDbPth, accessDbPath, true);

                File.Delete(tempDbPth);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(objJRO);
                objJRO = null;
                System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
            }

            catch (Exception e)
            {
         //       MessageBox.Show("压缩MDB文件" + accessDbPath + "发生错误,提示如下:" + "\r\n" + e.Message.ToString());
            }
            finally
            {

            }
        }　



        private void button1_Click_1(object sender, EventArgs e)
        {
            string ss = @"c:\SysSet.mdb";
         //   CompressAccess(ss,string.Empty);
            string ext = System.IO.Path.GetExtension(ss);
            MessageBox.Show(ext);

        }

        private void button1_Click_2(object sender, EventArgs e)
        {
                        string ss = @"c:\SysSet.mdb";
                        CompactAccessDB(ss, string.Empty);
                        MessageBox.Show("OK");

        }

     

        private void button1_Click_3(object sender, EventArgs e)
        {

        }


        /// <summary>  
        /// 把DataTable的数据导出到Excel文件中  
        /// </summary>  
        /// <param name="fileName">Excel文件名</param>  
        /// <param name="dataTable">要导出的数据表</param>  
        /// <param name="errorInfo">操作出错信息</param>  
        /// <returns>是否导出成功</returns>  
        public static bool GenerateExcel(string fileName, DataTable dataTable, out string errorInfo)
        {
            errorInfo = null;

            object objApp;
            object objBook;
            object objBooks;
            object objSheets;
            object objSheet;
            object objCells;
            object[] Parameters;

            if (dataTable == null || dataTable.Rows.Count == 0)
            {
                return true;
            }

            try
            {
                // 获取Excel类型并建立其实例  
                Type objExcelType = Type.GetTypeFromProgID("Excel.Application");
                if (objExcelType == null)
                {
                    return false;
                }
                objApp = Activator.CreateInstance(objExcelType);
                if (objApp == null)
                {
                    return false;
                }
                //获取Workbook集  
                objBooks = objApp.GetType().InvokeMember("Workbooks", BindingFlags.GetProperty, null, objApp, null);

                //添加一个新的Workbook  
                objBook = objBooks.GetType().InvokeMember("Add", BindingFlags.InvokeMethod, null, objBooks, null);

                //获取Sheet集  
                objSheets = objBook.GetType().InvokeMember("Worksheets", BindingFlags.GetProperty, null, objBook, null);

                //获取第一个Sheet对象  
                Parameters = new Object[1] { 1 };
                objSheet = objSheets.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, objSheets, Parameters);

                try
                {
                    //写入表头信息  
                    for (int i = 0; i < dataTable.Columns.Count; i++)
                    {
                        Parameters = new Object[2] { 1, i + 1 };
                        objCells = objSheet.GetType().InvokeMember("Cells", BindingFlags.GetProperty, null, objSheet, Parameters);
                        //向指定单元格填写内容值  
                        Parameters = new Object[1] { dataTable.Columns[i].Caption };
                        objCells.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, objCells, Parameters);
                    }
                    //写入表中数据内容  
                    for (int i = 0; i < dataTable.DefaultView.Count; i++)
                    {
                        for (int col = 0; col < dataTable.Columns.Count; col++)
                        {
                            Parameters = new Object[2] { i + 2, col + 1 };
                            objCells = objSheet.GetType().InvokeMember("Cells", BindingFlags.GetProperty, null, objSheet, Parameters);
                            //向指定单元格填写内容值  
                            Parameters = new Object[1] { dataTable.DefaultView[i][col].ToString() };
                            objCells.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, objCells, Parameters);
                        }
                    }
                }
                catch (Exception operExce)
                {
                    errorInfo = operExce.Message;
                    return false;
                }
                finally
                {
                    //不提示保存  
                    //Parameters = new Object[1] { false };
                    //objApp.GetType().InvokeMember("DisplayAlerts", BindingFlags.SetProperty, null, objApp, Parameters);

                    //保存文件并退出  
                    Parameters = new Object[1] { fileName };
                    objBook.GetType().InvokeMember("SaveAs", BindingFlags.InvokeMethod, null, objBook, Parameters);
                    objApp.GetType().InvokeMember("Quit", BindingFlags.InvokeMethod, null, objApp, null);
                }
                return true;
            }
            catch (Exception appExce)
            {
                errorInfo = appExce.Message;
                return false;
            }
        }

        private void button1_Click_4(object sender, EventArgs e)
        {
            string sourceFile = @"D:\Projects\MyAPP\exe\client\Model\JPD_SendMemo_201207260915248551.xls";
            File.Delete(sourceFile);
        }

        private void btnsave_Click(object sender, EventArgs e)
        {
            try
            {
                this.gridEx1.EndEdit();
                this.bindingSource1.EndEdit();
            }
            catch (Exception ex)
            {
                MsgTools.ErrorMsg(ex.Message.ToString());
            }

            if (this.dataTableEx1.DataTable.GetChanges() != null)
            {
                if (dataTableEx1.Save)
                {
                    MsgTools.InfoMsg("数据提交成功!");
                    this.dataTableEx1.DataTable.AcceptChanges();
                }
                else
                {
                    //删除失败,刷新数据
                    MsgTools.InfoMsg("数据提交失败!");
                }
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (MsgTools.QuestionMsg("取消提交数据?"))
            {
                try
                {
                    this.gridEx1.CancelEdit();
                    this.bindingSource1.CancelEdit();
                }
                catch
                {
                }
                if (this.dataTableEx1.DataTable.GetChanges() != null)
                {
                    this.dataTableEx1.DataTable.RejectChanges();
                }
            }
        }


        private void btnAdd_Click(object sender, EventArgs e)
        {
            this.bindingSource1.AddNew();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (this.gridEx1.CurrentRow == null)
            {
                MsgTools.ErrorMsg("删除失败!请先选中行后再执行.");
                return;
            }

            int index = this.gridEx1.CurrentRow.Index;    //取得选中行的索引 

            string DeleteMsg = "";


            //单选删除
            if (!MsgTools.QuestionMsg("确定删除当前记录?")) { return; }
            this.bindingSource1.RemoveCurrent();
        }

        private void btnFind_Click(object sender, EventArgs e)
        {
            string strSQL = "SELECT * FROM MySQL";
            if (txtFind.Text != string.Empty)
            {
                strSQL = strSQL + " Where (cKey like '%" + txtFind.Text + "%')";
            }
            this.dataTableEx1.Text = strSQL;
            this.dataTableEx1.DataBinds();

            this.bindingSource1.DataSource = this.dataTableEx1.DataTable;
        }

        private void txtFind_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                btnFind.PerformClick();
            } 
        }


    }
}
